package com.szzg10.thinking.chapter18;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

public class TextFile extends ArrayList<String> {

	public static void main(String[] args) throws IOException {
		TextFile textFile = new TextFile();
		textFile.write("Hello World!");
	}
	
	public TextFile() throws IOException {
		super(Arrays.asList(read().split("\n")));
		
		if(get(0).equals("")) {
			remove(0);
		}
	}
	
	private static String read() throws IOException {
		File file = new File(BasicFileOutput.FILE_NAME_OUT);
		FileReader fileReader = new FileReader(file);
		BufferedReader reader = new BufferedReader(fileReader);
		
		StringBuilder builder = new StringBuilder();
		String str;
		while((str = reader.readLine()) != null) {
			builder.append(str + "\n");
		}
		reader.close();
		
		return builder.toString();
	}
	
	private void write(String str) throws FileNotFoundException {
		File file = new File(BasicFileOutput.FILE_NAME_OUT);
		PrintWriter writer = new PrintWriter(file);
		
		for(String element: this) {
			writer.println(element);
		}
		writer.println(str);
		writer.close();
	}
}
